<?php
/**
 * Description: 模考、估分列表
 * User: devforma
 * Date: 15/7/13
 * Time: 17:05
 */

class MockExerciseList implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        $isLogin = validateUser($queryArgs) === 1;

        $mockSetting = getOption('mokaoManage');

        $available = $mockSetting['available'];
        if (!empty($queryArgs['debug']) && $queryArgs['debug'] == '1') {
            $available = true;
        }

        if (empty($mockSetting) || !$available)
            return genOutput(1001);

        if ($mockSetting['type'] === 'mock') {
            $list = $cmsdb->getResults("SELECT `id`, `paper_name`, `persons_num` FROM `data_test_paper`
            WHERE `id` IN ({$mockSetting['papers']}) ORDER BY FIELD(`id`, {$mockSetting['papers']})");
        } else {
            $list = $cmsdb->getResults("SELECT `id`, `name` AS paper_name FROM `original_ztk_papers`
            WHERE `id` IN ({$mockSetting['papers']}) ORDER BY FIELD(`id`, {$mockSetting['papers']})");
        }

        $paperType = $mockSetting['type'] === 'mock' ? 8 : 7;

        if ($isLogin) {
            //获取用户已做模考试卷
            $doneList = $cmsdb->getResults('SELECT `id`, `paper_id`, `status` FROM `qb_relationship_user_paper`
            WHERE `user_id`=:uid AND `paper_type`=:ptype', array(':uid' => $queryArgs['user_id'], ':ptype' => $paperType));

            $status = array('1' => 'done', '2' => 'undone', '0' => 'fresh');
            foreach($doneList as $dl) {
                $done[$dl->paper_id] = array(
                    'exercise_id' => intval($dl->id),
                    'status' => $status[$dl->status]
                );
            }

        }

        $paperList = array();
        foreach ($list as $l) {
            if ($mockSetting['type'] === 'mock') {
                $persons_num = intval($l->persons_num);
            } else {
                $persons_num = intval($cmsdb->getVar("SELECT COUNT(*) FROM `qb_relationship_user_paper`
                WHERE `paper_id`=:pid AND `paper_type`=:ptype", array(':pid' => $l->id, ':ptype' => $paperType)));
            }

            $paperList[] = array(
                'id' => intval($l->id),
                'exercise_id' => $isLogin && isset($done[$l->id]) ? $done[$l->id]['exercise_id'] : 0,
                'name' => $l->paper_name,
                'persons_num' => $persons_num,
                'status' => $isLogin && isset($done[$l->id]) ? $done[$l->id]['status'] : 'fresh'
            );
        }

        return genOutput(1, array(
            'name' => $mockSetting['name'],
            'type' => $mockSetting['type'],
            'paper_list' => $paperList
        ));

    }
}